package agent

import (
	"context"

	"gitee.com/liuxuezhan/ar-platform/admin-api/internal/svc"
	"gitee.com/liuxuezhan/ar-platform/admin-api/internal/types"
	"gitee.com/liuxuezhan/ar-platform/rpc-client/agentClient/rpc"
	"gitee.com/liuxuezhan/ar-platform/rpc-client/gameManageClient/client/game"
	"gitee.com/liuxuezhan/ar-platform/rpc-client/userServiceClient/userrpc"
	"github.com/zeromicro/go-zero/core/logx"
)

type FlowRebatesLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// 流水返佣
func NewFlowRebatesLogic(ctx context.Context, svcCtx *svc.ServiceContext) *FlowRebatesLogic {
	return &FlowRebatesLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *FlowRebatesLogic) FlowRebates(req *types.FlowRebatesReq) (resp *types.FlowRebatesResp, err error) {
	flow, err := l.svcCtx.AgentRPC.GetCommissionsFlow(context.Background(), &rpc.GetCommissionsFlowReq{
		Day:      req.Day,
		UserId:   req.UserId,
		Tier:     req.Tier,
		Search:   req.Search,
		Page:     req.Page,
		PageSize: req.PageSize,
	})
	if err != nil {
		return nil, err
	}

	categoryList, err := l.svcCtx.GameManageRpc.GameCategoryList(context.Background(), &game.GameCategoryListReq{IsEnabled: 1})
	if err != nil {
		return nil, err
	}
	categoryMap := make(map[string]string)
	for _, v := range categoryList.List {
		categoryMap[v.Code] = v.Name
	}

	list := make([]types.CommissionFlowItem, len(flow.Data))
	for _i, _row := range flow.Data {
		// 获取基本信息
		userBaseInfo, err := l.svcCtx.UserServiceRPC.UserGetByClient(l.ctx, &userrpc.UserGetByClientRequest{
			Id: _row.UserId,
		})
		if err != nil {
			return nil, err
		}
		commissionTypeItem := make([]types.CommissionTypeItem, len(_row.GetList()))
		for j, v2 := range _row.GetList() {
			v2.CategoryName = categoryMap[v2.CategoryCode]
			commissionTypeItem[j] = types.CommissionTypeItem{
				CategoryCode:     v2.CategoryCode,
				CategoryName:     v2.CategoryName,
				GameAmount:       v2.GameAmount,
				Tier:             v2.Tier,
				CommissionAmount: v2.CommissionAmount,
			}
		}
		list[_i] = types.CommissionFlowItem{
			UserId:             _row.UserId,
			Mobile:             userBaseInfo.User.Phone,
			Email:              userBaseInfo.User.Email,
			CommissionsAmount:  _row.CommissionsAmount,
			CommissionTypeItem: commissionTypeItem,
		}
	}

	resp = &types.FlowRebatesResp{
		CommissionFlowItem: list,
		Total:              flow.Total,
		Page:               flow.Page,
		PageSize:           flow.PageSize,
	}

	return
}
